package com.xtiim.battery.discharge.modules.htm.controller;

import cn.hutool.core.util.StrUtil;
import com.xtiim.battery.discharge.common.Constants;
import com.xtiim.battery.discharge.common.api.CommonPage;
import com.xtiim.battery.discharge.common.api.CommonResult;
import com.xtiim.battery.discharge.modules.htm.model.HostInfo;
import com.xtiim.battery.discharge.modules.htm.param.HostInfoCreatParam;
import com.xtiim.battery.discharge.modules.htm.param.HostInfoQueryParam;
import com.xtiim.battery.discharge.modules.htm.param.HostInfoUpdateParam;
import com.xtiim.battery.discharge.modules.htm.service.HostInfoService;
import com.xtiim.battery.discharge.modules.htm.service.impl.HostInfoServiceImpl;
import com.xtiim.battery.discharge.persistence.IPage;
import com.xtiim.battery.discharge.util.GsonUtil;
import com.xtiim.battery.discharge.util.PageUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
public class HostInfoController extends HttpServlet {

    private HostInfoService hostInfoService = HostInfoServiceImpl.getInstance();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/htm/host_info")) {
            getHostInfoList(request, response);
        } else if (requestURI.equals("/htm/host_info/delete")) {
            deleteHostInfo(request, response);
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/htm/host_info/add")) {
            createHostInfo(request, response);
        } else if (requestURI.equals("/htm/host_info/update")) {
            updateHostInfo(request, response);
        }
    }

    private void createHostInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(Constants.HTTP_RESPONSE_CONTENT_TYPE);
            response.setCharacterEncoding(Constants.CHARACTER_ENCODING);

            StringBuffer sb = new StringBuffer();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            if (StrUtil.isBlank(sb)) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("param is null")));
                return;
            }

            HostInfoCreatParam createParam = GsonUtil.fromJson(sb.toString(), HostInfoCreatParam.class);
            if (createParam == null) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("createParam is null")));
                return;
            }

            HostInfo hostInfo = hostInfoService.selectHostInfo(createParam.getName(), createParam.getNumber());
            if (hostInfo != null) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("主机名称或主机编号已经存在，请重新输入！")));
                return;
            }

            Boolean result = hostInfoService.create(createParam);
            if (result) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.success()));
            } else {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            }
        } catch (Exception e) {
            log.error("create host info error", e);
            try {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    private void updateHostInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(Constants.HTTP_RESPONSE_CONTENT_TYPE);
            response.setCharacterEncoding(Constants.CHARACTER_ENCODING);

            StringBuffer sb = new StringBuffer();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            if (StrUtil.isBlank(sb)) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("param is null")));
                return;
            }

            HostInfoUpdateParam updateParam = GsonUtil.fromJson(sb.toString(), HostInfoUpdateParam.class);
            if (updateParam == null) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("updateParam is null")));
                return;
            }

            if (updateParam.getId() == null) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("updateParam id is null")));
                return;
            }

            HostInfo hostInfo = hostInfoService.selectHostInfo(updateParam.getName(), null);
            if (hostInfo != null && !Objects.equals(hostInfo.getId(), updateParam.getId())) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("主机名称已经存在，请重新输入！")));
                return;
            }

            hostInfo = hostInfoService.selectHostInfo(null, updateParam.getNumber());
            if (hostInfo != null && !Objects.equals(hostInfo.getId(), updateParam.getId())) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("主机编号已经存在，请重新输入！")));
                return;
            }

            Boolean result = hostInfoService.update(updateParam);
            if (result) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.success()));
            } else {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            }
        } catch (Exception e) {
            log.error("update host info error", e);
            try {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    private void getHostInfoList(HttpServletRequest request, HttpServletResponse response) {
        try {

            response.setContentType(Constants.HTTP_RESPONSE_CONTENT_TYPE);
            response.setCharacterEncoding(Constants.CHARACTER_ENCODING);

            HostInfoQueryParam queryParam = new HostInfoQueryParam();
            String name = request.getParameter("name");
            queryParam.setName(name);

            String number = request.getParameter("number");
            queryParam.setNumber(number);

            String usePage = request.getParameter("usePage");
            queryParam.setUsePage(StrUtil.isBlank(usePage) ? Boolean.TRUE : Boolean.valueOf(usePage));

            Integer[] pair = PageUtil.convertOrDefault(request.getParameter("pageNo"), request.getParameter("pageSize"));
            queryParam.setPageNo(pair[0]).setPageSize(pair[1]);
            if (queryParam.getUsePage()) {
                IPage<HostInfo> page = hostInfoService.getHostInfo(queryParam);
                response.getWriter().write(GsonUtil.toJson(CommonResult.success(CommonPage.restPage(page))));
            } else {
                List<HostInfo> list = hostInfoService.getHostInfo(queryParam);
                response.getWriter().write(GsonUtil.toJson(CommonResult.success(list)));
            }

        } catch (Exception e) {
            log.error("query host info page or list error", e);
            try {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    private void deleteHostInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(Constants.HTTP_RESPONSE_CONTENT_TYPE);
            response.setCharacterEncoding(Constants.CHARACTER_ENCODING);

            String id = request.getParameter("id");
            if (StrUtil.isBlank(id)) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed("id is null")));
                return;
            }

            Boolean result = hostInfoService.deleteHostInfo(Long.valueOf(id));
            if (result) {
                response.getWriter().write(GsonUtil.toJson(CommonResult.success()));
            } else {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            }
        } catch (Exception e) {
            log.error("delete host info error", e);
            try {
                response.getWriter().write(GsonUtil.toJson(CommonResult.failed()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
